package com.study.it.hystrix.command;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;

import java.lang.reflect.Method;
//通用的
public class HyCommand<T> extends HystrixCommand<T> {
    private Object[] params;
    private Method method=null;
    private Object remoteService=null;
    private T failObj;
    public HyCommand(Object _remoteService,Method _method
            ,T _failObj,Object[] _params) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("myGroup"))
                /* 配置依赖超时时间,500毫秒*/
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionIsolationThreadTimeoutInMilliseconds(500)));
        this.remoteService=_remoteService;
        this.method=_method;
        this.params=_params;
        this.failObj=_failObj;
    }

    public HyCommand(Object _remoteService,String _methodname,Object[] _params,T _failObj )
    {
            this(_remoteService,null,_failObj,_params);
            try{
                Class[] classes=new Class[params==null?0:params.length];
                if(_params!=null)
                    for(int i=0;i<_params.length;classes[i]=_params[i].getClass(),i++);
                this.method=_remoteService.getClass().getMethod(_methodname,classes);
                System.out.println(this.method.getName());

           }catch(Exception ex)
            {
                ex.printStackTrace();
                throw new RuntimeException(ex);
            }
    }


    @Override
    protected T getFallback() {
        return this.failObj;
    }

    @Override
    protected T run() throws Exception {
        try {
            System.out.println("hystrix调用方法");
            return (T) method.invoke(remoteService, params);
        }catch (Exception ex)
        {
            ex.printStackTrace();
            throw ex;
        }
    }

}
